#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "pbc.h"
#include "readfile.h"


#define COUNT 1000000

struct pbc_wmessage * test_wmessage(struct pbc *p)
{
    struct pbc_wmessage *m = pbc_wmessage_create(p, "address");

    pbc_encode_int32(m, "id", 150);
    pbc_encode_int64(m, "ud", -2);
    pbc_encode_string(m, "path", "beijing");

    pbc_encode_int32(m, "icons", 80);
    pbc_encode_int32(m, "icons", 78);
    pbc_encode_int32(m, "icons", -10078);
    
    pbc_encode_int64(m, "bignum", 199999000000);
    pbc_encode_int64(m, "bignum", 8888888888844);
    

    struct pbc_wmessage *si = pbc_wmessage_message(m, "si");
    pbc_encode_int32(si, "aa", -650);

    si = pbc_wmessage_message(m, "si");
    pbc_encode_int32(si, "aa", 120);

    pbc_encode_float(m, "pointway", 12.4454);

    return m;
}

void test_rmessage(struct pbc *p, struct chumk *ck)
{
    int i, n;

    struct pbc_rmessage *rmsg = pbc_rmessage_create(p, "address", ck);

    int id = pbc_decode_int32(rmsg, "id", 0, 0);
    printf("id = %d\n", id);

    int64_t ud = pbc_decode_int64(rmsg, "ud", 0, 0);
    printf("ud = %ld\n", ud);

    const char *path = pbc_decode_string(rmsg, "path", 10, NULL);
    printf("path = %s\n", path);


    float pointway = pbc_decode_float(rmsg, "pointway", 0, 0);
    printf("pointway = %f\n", pointway);

    n = pbc_rmessage_size(rmsg, "si");

    for (i = 0; i < n; ++i)
    {
        struct pbc_rmessage *si = pbc_rmessage_message(rmsg, "si", i);
        assert(si);
        int aa = pbc_decode_int32(si, "aa", i, 0);
        printf("aa = %d\n", aa);
    }


    n = pbc_rmessage_size(rmsg, "icons");
    printf("icons size: %d\n", n);
    for (i = 0; i < n; ++i)
    {
        int icons = pbc_decode_int32(rmsg, "icons", i, 0);
        printf("icons: %d\n", icons);
    }

    n = pbc_rmessage_size(rmsg, "bignum");
    for (i = 0; i < n; ++i)
    {
        int64_t bignum = pbc_decode_int64(rmsg, "bignum", i, 0);
        printf("bignum: %ld\n", bignum);
    }
    
    pbc_rmessage_free(rmsg);
}


int main(int argc, char const *argv[])
{
    char *buf = NULL;
    int err = readfile("test.proto", &buf);
    if (err < 0)
        return 1;

    struct chumk ck;

    struct pbc *p = pbc_parser(buf);
    assert(p);

    struct pbc_wmessage *m = test_wmessage(p);

    pbc_wmessage_buffer(m, &ck);

    int i;
    for (i = 0; i < ck.len; ++i)
    {
        printf("%02x ", ck.buffer[i]);
    }
    printf("\n");
    printf("< write buffer size: %d >\n\n", ck.len);

    test_rmessage(p, &ck);

    pbc_wmessage_free(m);
    pbc_free(p);
    free(buf);

    return 0;
}



